package org.schat;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Description 服务端
 * @Author lsh
 * @Date 2020-03-18 19:16
 **/
public class IMServer {
	public static ExecutorService executors=Executors.newFixedThreadPool(200);
	public static LinkedBlockingQueue<MessageDomain> msgQue=new LinkedBlockingQueue<MessageDomain>();
	public static ConcurrentHashMap<String, ClientDomain> clientMap=new ConcurrentHashMap<String, ClientDomain>();

	public static void main(String[] args) {
        startServer();
	}

	public static void startServer(){
        try {
            ServerSocket serverSocket=new ServerSocket(10086);
            //状态监测
            executors.execute(new OnlineStatusRunnable());
            executors.execute(new OnlineNumRunnable());
            //接收请求
            executors.execute(new SocketAcceptRunnable(serverSocket));
            //群发消息
            executors.execute(new SendMsgToAllRunnable());
            executors.execute(new SendMsgToAllRunnable());
            executors.execute(new SendMsgToAllRunnable());
            executors.execute(new SendMsgToAllRunnable());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	
	public static void sendMsgToClient(Socket socket,String type,String msg){
		synchronized (socket){
			JSONObject jsonObject =  new JSONObject();
			jsonObject.put("type",type);
			jsonObject.put("msg",msg);
			try {
				OutputStream output = socket.getOutputStream();
				output.write(jsonObject.toJSONString().getBytes("UTF-8"));
				output.write('\n');
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
		
	public static void sendAllClient(MessageDomain msg){
		Set<Entry<String, ClientDomain>> clientSet=IMServer.clientMap.entrySet();
		for(Entry<String, ClientDomain> entry:clientSet){
			ClientDomain clientDomain=entry.getValue();
			sendMsgToClient(clientDomain.getSocket(),msg.getType(),msg.getMsg());
		}
	}

    //清除客户端对象
    public static void removeClient(ClientDomain clientDomain) {
		//关闭连接
        clientDomain.closeSocket();
        IMServer.clientMap.remove(clientDomain.getId());
    }
}
